<?php
namespace app\admin\model;

use think\Config;
use think\Db;
use think\Loader;
use think\Model;
use traits\model\SoftDelete;
use think\Session;
use think\Request;

class Article extends Admin
{





    public function getList( $request )
	{
		$request = $this->fmtRequest( $request );

		$data = $this->alias('s')
                ->join('category p','s.cid = p.id','left')->field('s.id,p.name as cid,s.title,s.faceimg,s.status,s.seo_title,s.seo_keys,s.seo_desc,s.create_time')
                ->order('create_time desc')
                ->where( $request['map'] )
                ->limit($request['offset'], $request['limit'])
                ->select();
		return $this->_fmtData( $data );
	}

	public function saveData( $data )
	{
		if( isset( $data['id']) && !empty($data['id'])) {
			$result = $this->edit( $data );
		} else {
			$result = $this->add( $data );
		}
		return $result;
	}

	public function add(array $data = [])
	{
		$ArticleValidate = validate('Article');
		if(!$ArticleValidate->scene('add')->check($data)) {
			return info(lang($ArticleValidate->getError()), 4001);
		}
		//获取编辑用户当前id# USE think\Session
        $userRow = Session::get('userinfo', 'admin');
        $data['uid'] = $userRow['id'];
        $data['cid'] = intval ($data['cid']);
//        var_dump($data);die;
		$this->allowField(true)->save($data);
		if($this->id > 0){
            return info(lang('Add succeed'), 1, '', $this->id);
        }else{
            return info(lang('Add failed') ,0);
        }
	}

	public function edit(array $data = [])
	{
		$ArticleValidate = validate('Article');
		if(!$ArticleValidate->scene('edit')->check($data)) {
			return info(lang($ArticleValidate->getError()), 4001);
		}

		$res = $this->allowField(true)->save($data,['id'=>$data['id']]);
		if($res == 1){
            return info(lang('Edit succeed'), 1);
        }else{
            return info(lang('Edit failed'), 0);
        }
	}

	public function deleteById($id)
	{
		$result = Article::destroy($id);
		if ($result > 0) {
            return info(lang('Delete succeed'), 1);
        }   
	}

	//格式化数据
	private function _fmtData( $data )
	{
		if(empty($data) && is_array($data)) {
			return $data;
		}

		foreach ($data as $key => $value) {

			$data[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
			$data[$key]['status'] = $value['status'] == 1 ? lang('Start') : lang('Off');
		}

		return $data;
	}

}
